package com.cloud.bc.controller.pay;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.cloud.bc.controller.BaseController;
import com.cloud.bc.model.domain.UserInfo;
import com.cloud.bc.model.entity.BcPaymenorders;
import com.cloud.bc.model.entity.BcSetmealOrders;
import com.cloud.bc.service.BcPaymenordersService;
import com.cloud.bc.service.BcSetmealOrdersService;
import com.cloud.bc.service.BcSetmealsService;
import com.cloud.bc.service.BcUsersService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

//PC收银台
@Controller
@AllArgsConstructor
@RequestMapping("pay")
public class PcPayController extends BaseController {
    private final BcUsersService bcUsersService;
    private final BcPaymenordersService bcPaymenordersService;

    /**
     * 收银台
     */
    @SneakyThrows
    @GetMapping("pay/{source}/{orderId}")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response,
                              @PathVariable("source") String source,
                              @PathVariable("orderId") String orderId) {
        String viewUrl =source.replace("pc","");
        if (StrUtil.isEmpty(orderId)) {
            //单号是空说明有人篡改数据
            PrintWriter writer = response.getWriter();
            writer.write("<script>alert('系统错误，请不要篡改信息!');window.location='/" + viewUrl + "';</script>");
        }
        ModelAndView view = baseView(request, "收银台-用户中心", source + "/pay/index");
        UserInfo userInfo = bcUsersService.getUserInfo(request);
        view.addObject("bodyCss", " page_pay");

        BcPaymenorders bcPaymenorders = new BcPaymenorders();
        bcPaymenorders.setUserId(userInfo.getId());
        bcPaymenorders.setOrderId(orderId);
        BcPaymenorders bcPaymenordersResult = bcPaymenordersService.selectOne(bcPaymenorders);
        if (null == bcPaymenordersResult || Convert.toInt(bcPaymenordersResult.getId(), 0) <= 0) {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write("<script>alert('系统错误，请不要篡改信息!');window.location='/" + viewUrl + "';</script>");
            return null;
        }
        view.addObject("setmeal", bcPaymenordersResult);

        //这里创建收银台订单

        return view;
    }

}
